package com.qf.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.pojo.R;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;

@Component
@Order(-5)
public class MyWebExceptionHandler implements WebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        try {
            URI uri = exchange.getRequest().getURI();
            String s = uri.toString();

            R r = R.error().putMsg("访问路径不合法，请检查访问路径或者请求参数，当前访问路径是：" + s);

            String json = new ObjectMapper().writeValueAsString(r);

            //利用响应对象，将这个结果提示信息写到浏览器
            ServerHttpResponse response = exchange.getResponse();
            DataBuffer wrap = response.bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));

            //解决响应中文乱码问题
            response.getHeaders().add("content-type","application/json;charset=utf-8");

            Mono<DataBuffer> mono = Mono.just(wrap);

            return response.writeWith(mono);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


        return null;
    }
}
